import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 直接测试星火 API 的认证方式
 */
public class DirectApiTest {
    
    public static void main(String[] args) {
        System.out.println("=== 直接测试星火 API ===");
        
        String apiKey = "ccVOLyaxCHSufHuoEqpc:WjfDEzvgefNiePBIlzdz";
        String baseUrl = "https://spark-api-open.xf-yun.com/v1/chat/completions";
        
        testApiCall(apiKey, baseUrl);
    }
    
    private static void testApiCall(String apiKey, String baseUrl) {
        System.out.println("API Key: " + apiKey);
        System.out.println("Base URL: " + baseUrl);
        
        try {
            URL url = new URL(baseUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setDoOutput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(60000);
            
            String requestBody = "{\"model\":\"4.0Ultra\",\"messages\":[{\"role\":\"user\",\"content\":\"你好，请简单回复\"}],\"max_tokens\":100}";
            System.out.println("请求体: " + requestBody);
            
            try (OutputStream os = connection.getOutputStream()) {
                os.write(requestBody.getBytes("UTF-8"));
                os.flush();
            }
            
            int responseCode = connection.getResponseCode();
            System.out.println("响应状态码: " + responseCode);
            
            InputStream inputStream = responseCode >= 200 && responseCode < 300 
                ? connection.getInputStream() 
                : connection.getErrorStream();
                
            StringBuilder response = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
            
            System.out.println("响应内容: " + response.toString());
            
            if (responseCode == 200) {
                System.out.println("✅ API 调用成功！");
            } else {
                System.err.println("❌ API 调用失败，状态码: " + responseCode);
            }
            
        } catch (Exception e) {
            System.err.println("❌ 测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
